package net.lab1024.sa.admin.module.crawler.service;

import com.alibaba.fastjson2.JSONArray;
import com.alibaba.fastjson2.JSONObject;
import com.esotericsoftware.minlog.Log;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.crawler.domain.form.*;
import net.lab1024.sa.admin.module.crawler.domain.jddj.*;
import net.lab1024.sa.admin.util.JddjUtils;
import net.lab1024.sa.admin.util.MtcyUtils;
import net.lab1024.sa.base.common.exception.BusinessException;
import net.lab1024.sa.base.common.util.SmartStringUtil;
import net.lab1024.sa.base.constant.TpTypeConst;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

@Slf4j
@Component
public class TpUtilService {

    @Autowired
    MtcyUtils mtcyUtils;
    @Autowired
    JddjUtils jddjUtils;

    public String getMtRequestUrl(String cookiestr, Integer pageNum) {
        return mtcyUtils.getMtRequestUrl(cookiestr, pageNum);
    }

    public List<ShopAddForm> authShop(ShopAddForm form) {
        List<ShopAddForm> shops = new ArrayList<>();
        String tp = form.getTp();
        String cookieStr = form.getCookiestr();
        if (TpTypeConst.MTCY.equals(tp)) {
            String shopListStr = mtcyUtils.getShopList(cookieStr);
            JSONObject obj = JSONObject.parseObject(shopListStr);
            JSONArray shopArray = obj.getJSONArray("data");
            if (!CollectionUtils.isEmpty(shopArray)) {
                Map<String, String> cookieMap = SmartStringUtil.cookieStrConvert(cookieStr);
                for (int i = 0; i < shopArray.size(); i++) {
                    JSONObject shopObj = shopArray.getJSONObject(i);
                    cookieMap.put("wmPoiId", shopObj.getString("id"));
                    ShopAddForm shopAddForm = ShopAddForm.builder()
                            .shopName(shopObj.getString("poiName"))
                            .shopId(shopObj.getString("id"))
                            .shopCategory(shopObj.getString("category"))
                            .shopStatus(shopObj.getString("businessDesc"))
                            .shopLogo(form.getShopLogo())
                            .cookiestr(SmartStringUtil.makeCookieStr(cookieMap))
                            .remark(form.getRemark())
                            .spId(form.getSpId())
                            .build();
                    shops.add(shopAddForm);
                }
            }
        }else if(TpTypeConst.JDCY.equals(tp)){
            JSONArray shopList = jddjUtils.getShopList(cookieStr);
            if(!CollectionUtils.isEmpty(shopList)){
                shopList.stream().map(shopObj -> (JSONObject) shopObj).forEach(shopObj -> {
                    String stationDeliveryStatus = shopObj.getString("stationDeliveryStatus");
                    if (StringUtils.isNoneBlank(stationDeliveryStatus) && stationDeliveryStatus.equals("2")) {
                        stationDeliveryStatus = "营业中";
                    }else{
                        stationDeliveryStatus = "其他状态";
                    }
                    ShopAddForm shopAddForm = ShopAddForm.builder()
                            .tp(form.getTp())
                            .shopName(shopObj.getString("stationName"))
                            .shopId(shopObj.getString("stationNo"))
                            .shopStatus(stationDeliveryStatus)
                            .shopLogo(shopObj.getString("logoUrl"))
                            .cookiestr(form.getCookiestr())
                            .remark(form.getRemark())
                            .spId(shopObj.getString("stationJdNo"))
                            .build();
                    shops.add(shopAddForm);
                });
            }
        }
        return shops;
    }

    public List<ShopTagForm> getshopTags(String cookieStr) {
        List<ShopTagForm> tags = new ArrayList<>();
        String responText = jddjUtils.getTagList(cookieStr);
        log.info("get-shop-tag:{}",responText);
        JSONObject responObj = JSONObject.parseObject(responText);
        jddjUtils.checkResult(responObj);
        JSONArray dataArray = responObj.getJSONArray("result");
        if(!CollectionUtils.isEmpty(dataArray)){
            dataArray.stream().map(tag -> (JSONObject) tag).forEach(tag -> {
                ShopTagForm form = ShopTagForm.builder()
                        .tagId(tag.getString("id"))
                        .tagName(tag.getString("shopCategoryName"))
                        .seq(tag.getInteger("sort"))
                        .build();
                tags.add(form);
            });
        }
        return tags;
    }

    public String createShopTag(String cookieStr, String name) {
        String respText = jddjUtils.createTag(cookieStr, name);
        JSONObject responObj = JSONObject.parseObject(respText);
        try {
            jddjUtils.checkResult(responObj);
        } catch (Exception e) {
            sleep(600);
            responObj = JSONObject.parseObject(respText);
            jddjUtils.checkResult(responObj);
        }
        JSONObject resultObj = responObj.getJSONObject("result");
        return resultObj.getString("id");
    }

    public JdItemDto getJdItem(String cookieStr, ShopItemForm form, Map<String, ShopTagForm> old2newShopTagMap, List<String> wmCategoryIds) {
        String description = form.getDescription();
        String name = form.getName();
        if (StringUtils.isBlank(form.getPicture())) {
            throw new BusinessException("菜品没有图片");
        }
        JdItemDto jddj = JdItemDto.builder()
                .brandId(35247L)
                .brandName("其他品牌")
                .title(name)
                .skuName(name)
                //不支持7天无理由退货
                .specialAttr(Arrays.asList("10:1"))
                //非单点配送
                .noSingleOrder(1)
                //视频id
                .productVideoId("-1")
                //是否展示图文详情
                .ifViewDesc(0)
                //广告语
                .slogan(StringUtils.isNoneBlank(description) && description.length() > 80 ? description.substring(0,
                        80) : description)
                .build();
        //通过名称预测类目
        String categoryRecommendStr = jddjUtils.getCategoryRecommend(cookieStr, name);
        JSONObject categoryRecommendObj = JSONObject.parseObject(categoryRecommendStr);
        try {
            jddjUtils.checkResult(categoryRecommendObj);
            JSONObject categoryRecommendResultObj = categoryRecommendObj.getJSONObject("result");
            if (categoryRecommendResultObj.getLong("recommendBrandId") != null) {
                jddj.setBrandId(categoryRecommendResultObj.getLong("recommendBrandId"));
                jddj.setBrandName(categoryRecommendResultObj.getString("recommendBrandName"));
            }
            JSONArray categoryIds = categoryRecommendResultObj.getJSONArray("categoryIds");
            if (!CollectionUtils.isEmpty(categoryIds)) {
                for (int i = 0; i < categoryIds.size(); i++) {
                    JSONArray firstCateIds = categoryIds.getJSONArray(i);
                    if (!CollectionUtils.isEmpty(firstCateIds)) {
                        //检查是否在营业范围内+是否可销售
                        String categoryInfoByPidText = jddjUtils.getCategoryInfoByPid(cookieStr, firstCateIds.getLong(0), 1);
                        if (!categoryInfoByPidText.contains("经营范围内") && jddjUtils.checkSaleAttrByCategoryId(cookieStr, firstCateIds.getLong(firstCateIds.size() - 1))) {
                            jddj.setFirstCategoryId(firstCateIds.getLong(0));
                            jddj.setSecondCategoryId(firstCateIds.getLong(1));
                            jddj.setCategoryId(firstCateIds.getLong(firstCateIds.size() - 1));
                            break;
                        }
                    }
                }
            }
        } catch (Exception e) {
        }
        //判断是否有类目
        if (jddj.getCategoryId() == null) {
            //随机外卖美食取一个
            Random r = new Random();
            int rindex = r.nextInt(wmCategoryIds.size());
            String fullPath = wmCategoryIds.get(rindex);
            String[] cs = fullPath.split(",");
            jddj.setFirstCategoryId(Long.parseLong(cs[0]));
            jddj.setSecondCategoryId(Long.parseLong(cs[1]));
            jddj.setCategoryId(Long.parseLong(cs[cs.length - 1]));
        }


        List<String> images = new ArrayList<>();
        try {
            String imageUrl = jddjUtils.uploadImg(cookieStr, form.getPicture());
            if (StringUtils.isNoneBlank(imageUrl)) {
                images.add(1 + ",,0000000000," + imageUrl);
            }
        } catch (Exception e) {
        }
        if (CollectionUtils.isEmpty(images)) {
            throw new BusinessException("上传图片出错");
        }
        jddj.setWareImgs(images);

        List<Long> shopCat = new ArrayList<>();
        shopCat.add(Long.parseLong(old2newShopTagMap.get(form.getTagId()).getTagId()));
        jddj.setShopCat(shopCat);

        //图文详情
        if (StringUtils.isNoneBlank(form.getDescription())) {
            jddj.setNotes("<p>" + form.getDescription() + "</p>");
        }


        String saleAttr = jddjUtils.getSaleAttrByCategoryIdAndSuperId(cookieStr, jddj.getCategoryId());
        List<JdAttrsDto> saleAttrList = JSONArray.parseArray(saleAttr, JdAttrsDto.class);
        if (CollectionUtils.isEmpty(saleAttrList)) {
            saleAttrList = new ArrayList<>();
            saleAttrList.add(JdAttrsDto.builder().saleAttrLevel(1).saleAttrName("份量").build());
        }
        String categoryAttrStr = jddjUtils.getCategoryAttr(cookieStr, jddj.getCategoryId());
        List<JdCategoryAttrsDto> jdCategoryAttrs = JSONArray.parseArray(categoryAttrStr, JdCategoryAttrsDto.class);
        List<String> categoryAttrList = new ArrayList<>();

        //类目属性
        jdCategoryAttrs.forEach(categoryAttr -> {
            List<JdAttrValueDto> attrValues = categoryAttr.getAttrValues();
            boolean isAdd = true;
            if (!CollectionUtils.isEmpty(attrValues)) {
                attrValues = attrValues.stream().filter(attr -> StringUtils.isNoneBlank(attr.getValueName())).collect(Collectors.toList());
                categoryAttr.setAttrValues(attrValues);
                isAdd = false;
            }
            if (!CollectionUtils.isEmpty(attrValues)) {
                //设置第一个选中
                if (JSONObject.toJSONString(attrValues).contains("Ⅱ类")) {
                    for (int i = 0; i < attrValues.size(); i++) {
                        JdAttrValueDto jdAttrValueDto = attrValues.get(i);
                        if (jdAttrValueDto.getValueName().equals("Ⅱ类") && StringUtils.isNoneBlank(jdAttrValueDto.getValueName())) {
                            categoryAttr.setValue(jdAttrValueDto.getKey());
                            break;
                        }
                    }
                } else {
                    categoryAttr.setValue(attrValues.get(0).getKey());
                }
            } else {
                if (isAdd) {
                    int elementType = categoryAttr.getElementType();
                    if (elementType == 6) {
                        categoryAttr.setValue("0");
                    } else if (elementType == 9) {

                    } else {
                        categoryAttr.setValue("见包装");
                    }
                }
            }
            categoryAttrList.add(categoryAttr.getId() + ":" + (StringUtils.isBlank(categoryAttr.getValue()) ? "" : categoryAttr.getValue()));
        });
        String tp = form.getTp();
        List<ShopItemSkuForm> skus = form.getSkus();
        skus.forEach(sku -> {
            if (StringUtils.isBlank(sku.getSpec())) {
                sku.setSpec(sku.getUnit());
            }
        });
        //属性名称表情字符修改,判重
        List<SpuCustomAttrDto> spuCustomAttrs = new ArrayList();
        List<ShopItemAttrForm> attrs = form.getAttrs();
        List<String> vals = new ArrayList<>();
        AtomicInteger no = new AtomicInteger(1);
        if (!CollectionUtils.isEmpty(attrs)) {
            attrs.forEach(attr -> {
                attr.setName(SmartStringUtil.filterEmoji(attr.getName()));
                if ("mtcy".equals(tp)) {
                    //美团餐饮
                    attr.setValue(SmartStringUtil.filterEmoji(attr.getValue()));
                    if (vals.contains(attr.getValue())) {
                        attr.setValue(attr.getValue() + no.getAndIncrement());
                    }
                    vals.add(attr.getValue());
                } else {
                    //饿了么餐饮
                    List<ShopItemAttrDetailsForm> details = attr.getDetails();
                    if (!CollectionUtils.isEmpty(details)) {
                        details.forEach(detail -> {
                            detail.setName(SmartStringUtil.filterEmoji(detail.getName()));
                            if (vals.contains(detail.getName())) {
                                detail.setName(detail.getName() + no.getAndIncrement());
                            }
                            vals.add(detail.getName());
                        });
                    }
                }
            });
        }
        Map<String, JdSaleValueRelationDto> relationMap = new HashMap<>();
        if ("mtcy".equals(tp)) {
            //美团餐饮
            //自定义属性
            attrs.stream().filter(attr -> !"2".equals(attr.getMode()))
                    .collect(Collectors.groupingBy(ShopItemAttrForm::getName,
                                    Collectors.mapping(ShopItemAttrForm::getValue, Collectors.toList())
                            )
                    ).forEach((k, v) -> {
                        spuCustomAttrs.add(SpuCustomAttrDto.builder()
                                .attrName(k)
                                .attrValues(String.join(",", v))
                                .build()
                        );
                    });
            //销售属性封装
            List<ShopItemAttrForm> attrForms = attrs.stream().filter(attr -> "2".equals(attr.getMode())).collect(Collectors.toList());
            if (attrForms == null) {
                JdAttrsDto jdAttrsDto = saleAttrList.get(0);
                jdAttrsDto.setSaleAttrName("份量");
                List<JdSaleValueRelationDto> saleValueRelations = new ArrayList<>();
                for (int i = 0; i < skus.size(); i++) {
                    ShopItemSkuForm sku = skus.get(i);
                    JdSaleValueRelationDto saleValueRelationDto = JdSaleValueRelationDto.builder()
                            .saleValueId(10L + i)
                            .saleValueName(sku.getSpec())
                            .build();
                    saleValueRelations.add(saleValueRelationDto);
                    relationMap.put(sku.getId(), saleValueRelationDto);
                }
                jdAttrsDto.setSaleValueRelation(saleValueRelations);
            } else {
                Map<String, List<ShopItemAttrForm>> attrsMap = attrForms.stream().collect(Collectors.groupingBy(ShopItemAttrForm::getName));
                List<String> attsNames = new ArrayList<>();
                attrForms.forEach(attr -> {
                    if (!attsNames.contains(attr.getName())) {
                        attsNames.add(attr.getName());
                    }
                });
                for (int j = 0; j < attsNames.size(); j++) {
                    String saleAttrName = attsNames.get(j);
                    List<ShopItemAttrForm> attrVals = attrsMap.get(saleAttrName);
                    if (j >= saleAttrList.size()) {
                        saleAttrList.add(JdAttrsDto.builder().saleAttrLevel(saleAttrList.size() - 1 + j).build());
                    }
                    JdAttrsDto jdAttrsDto = saleAttrList.get(j);
                    jdAttrsDto.setSaleAttrName(saleAttrName);
                    List<JdSaleValueRelationDto> saleValueRelations = new ArrayList<>();
                    for (int k = 0; k < attrVals.size(); k++) {
                        ShopItemAttrForm shopItemAttrForm = attrVals.get(k);
                        JdSaleValueRelationDto saleValueRelationDto = JdSaleValueRelationDto.builder()
                                .saleValueId(10L + k)
                                .saleValueName(shopItemAttrForm.getValue())
                                .build();
                        saleValueRelations.add(saleValueRelationDto);
                        relationMap.put(shopItemAttrForm.getId(), saleValueRelationDto);
                    }
                    jdAttrsDto.setSaleValueRelation(saleValueRelations);
                }
            }
        } else {
            //饿了么餐饮
            //自定义属性
            attrs.stream().forEach(attr -> {
                List<ShopItemAttrDetailsForm> details = attr.getDetails();
                List<String> detailNames = new ArrayList<>();
                details.stream().forEach(detail -> {
                    detailNames.add(detail.getName());
                });
                spuCustomAttrs.add(SpuCustomAttrDto.builder()
                        .attrName(attr.getName())
                        .attrValues(String.join(",", detailNames))
                        .build()
                );
            });
            //销售属性封装
            saleAttrList = saleAttrList.subList(0, 1);
            JdAttrsDto jdAttrsDto = saleAttrList.get(0);
            List<JdSaleValueRelationDto> saleValueRelations = new ArrayList<>();
            for (int i = 0; i < skus.size(); i++) {
                ShopItemSkuForm sku = skus.get(i);
                JdSaleValueRelationDto saleValueRelationDto = JdSaleValueRelationDto.builder()
                        .saleValueId(10L + i)
                        .saleValueName(sku.getSpec())
                        .build();
                saleValueRelations.add(saleValueRelationDto);
                relationMap.put(sku.getId(), saleValueRelationDto);
            }
            jdAttrsDto.setSaleValueRelation(saleValueRelations);
        }
        jddj.setAttrs(saleAttrList);
        jddj.setAllAttrs(saleAttrList);
        jddj.setSpuCustomAttrList(spuCustomAttrs);
        List<JdSkusDto> jdSkus = new ArrayList();
        Integer sellStatus = form.getSellStatus();
        for (ShopItemSkuForm sku : skus) {
            String weight = sku.getWeight();
            if (SmartStringUtil.isNotBlank(weight)) {
                weight = weight.replaceAll("[^0-9]", "");
            } else {
                weight = "1";
            }
            List<JdSaleValueRelationDto> saleValueRelationList = new ArrayList<>();
            if ("mtcy".equals(tp)) {
                //美团
                List<ShopItemSkuAttrForm> skuAttrs = sku.getSkuAttrs();
                if (!CollectionUtils.isEmpty(skuAttrs)) {
                    skuAttrs.forEach(skuAttr -> {
                        JdSaleValueRelationDto jdSaleValueRelationDto = relationMap.get(skuAttr.getSpu_attr_id());
                        if (jdSaleValueRelationDto == null) {
                            jdSaleValueRelationDto = relationMap.get(sku.getId());
                        }
                        saleValueRelationList.add(jdSaleValueRelationDto);
                    });
                }
            } else {
                //饿了么
                JdSaleValueRelationDto jdSaleValueRelationDto = relationMap.get(sku.getId());
                saleValueRelationList.add(jdSaleValueRelationDto);
            }
            jdSkus.add(JdSkusDto.builder()
                    //1上架2下架
                    .fixedStatus(sellStatus != null && sellStatus == 0 ? 1 : 2)
                    .saleValueRelationList(saleValueRelationList)
                    .weightDesc(Integer.parseInt(weight))
                    .specUnit("g")
                    .barCode(SmartStringUtil.createBarcode())
                    .outSkuId(sku.getId())
                    .skuPrice(sku.getPrice())
                    .stockNum("10000")
                    //打包费
                    .mf(sku.getBoxPrice())
                    .skuName(name)
                    .categoryAttrs(jdCategoryAttrs)
                    .categoryAttr(categoryAttrList)
                    .wareImgs(images)
                    .build()
            );
        }

        jddj.setCategoryAttr(categoryAttrList);
        jddj.setSkus(jdSkus);
        jddj.setSellCities(List.of("0"));
        jddj.setFixedStatus(sellStatus != null && sellStatus == 0 ? 1 : 2);
        //单点不送
        if (form.getDdbs() != null && form.getDdbs() == 1) {
            jddj.setNoSingleOrder(1007);
        }
        return jddj;
    }

    public JSONObject saveSpuProductInfo(String cookieStr,JdItemDto item){
        return  jddjUtils.saveSpuProductInfo(cookieStr,item);
    }

    public JSONArray skuQuery(String cookieStr, String name){
        return  jddjUtils.skuQuery(cookieStr,name,0);
    }

    public JSONArray querySpuList(String cookieStr, String name){
        return  jddjUtils.querySpuList(cookieStr,name,0);
    }
    public void updateWareUpStatus(String cookieStr, List<Long> ids, int status) {
        jddjUtils.updateWareUpStatus(cookieStr,ids,status);
    }
    public void updateCurrentQty(String cookieStr, String skuId, String shopId, Integer stock){
        if (stock==null || stock<1) {
            stock = 9999;
        }
        jddjUtils.updateCurrentQty(cookieStr,skuId,shopId,stock);
    }
    public List<String> getWaimaiRandomCategory(String cookieStr) {
        return jddjUtils.getWaimaiRandomCategory(cookieStr);
    }

    public void sleep(Integer timeout) {
        try {
            Thread.sleep(timeout);
        } catch (InterruptedException e) {
        }
    }
}
